// @ts-nocheck
import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import {UserOutlined} from '@ant-design/icons';
import {SettingDrawer} from '@ant-design/pro-components';
import type {RunTimeLayoutConfig} from '@umijs/max';
import {history} from '@umijs/max';
import {requestConfig} from './requestConfig';
import {getLoginUser, userLogout} from "@/services/CloudBridge-Service/userController";
import {Avatar, Button, message} from "antd";
import {useModel} from "@@/exports";

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const registerPath = '/user/register'


const Logout: React.FC = () => {
  const {initialState, setInitialState} = useModel('@@initialState');
  const handleLogout = async () => {
    try {
      // 注销
      const res = await userLogout({});
      if (res.data) {
        setInitialState({
          loginUser: undefined,
          ...initialState
        });
        history.push(loginPath);
        return;
      }
    } catch (error) {
      if (error.code === 50001) {
        history.push(loginPath);
        return;
      } else {
        const defaultLoginFailureMessage = '登出失败，请重试！';
        console.log(error);
        message.error(defaultLoginFailureMessage);
      }
    }
  };

  return (
    <>
      <Avatar icon={<UserOutlined/>}/>
      <Button type="text" onClick={handleLogout}>退出登录</Button>
    </>
  );

}


/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialState> {
  // 当页面首次加载时，获取要全局保存的数据，比如用户登录信息
  const state: InitialState = {
    loginUser: undefined,
  }
  try {
    const res = await getLoginUser();
    if (res.data) {
      state.loginUser = res.data;
    }
  } catch (error) {
    const urlParams = window.location.href.split('/')
    if (urlParams.contains('register')) {
      history.push(registerPath);
    } else history.push(loginPath);
  }
  return state;
}


// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {


  const setting = {
    "colorPrimary": "#1890ff",
    "colorWeak": false,
  }
  return {
    layout: "side",
    rightContentRender: () => <RightContent/>,
    waterMarkProps: {
      content: initialState?.loginUser?.userName,
    },
    footerRender: () => <Footer/>,
    onPageChange: () => {
      const {location} = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.loginUser && location.pathname !== loginPath && location.pathname != registerPath) {
        history.push(loginPath);
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    actionsRender: () => [],
    menuHeaderRender: undefined,
    links: isDev
      ? [
        // <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
        //   <LinkOutlined/>
        //   <span>OpenAPI 文档</span>
        // </Link>,、
        <Logout></Logout>
      ]
      : [],
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading/>;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login' || '/register') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={setting}
              onSettingChange={
                (settings) => {
                  setInitialState((preInitialState) => ({
                    ...preInitialState,
                    settings,
                  }));
                }}
            />
          )}
        </>
      );
    },
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = requestConfig;
